/**
 * 
 */
package pt.inescid.components.appadaptationlayer.applications.sumunifs;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import pt.inescid.utils.FileUtils;

/**
 * ATTENTION: The gnuplot application is required
 * 
 * @author Sergio Esteves (sesteves at gsd.inesc-id.pt)
 *
 */
public class BuildGraph {
	
	private static final String gnuplotExe = "gnuplot"; 

	private String tempDir;
	
	private int loadCount = 0;
	private Object loadCountLock = new Object();
	
	private int dataCount = 0;
	private Object dataCountLock = new Object();
	
	public BuildGraph(String tempDir) {
		this.tempDir = tempDir;
	}
	
	private String makeGnuLoadFile(String outputLocation, String dataLocation) {
		String configLocation;
		synchronized(loadCountLock) {
			configLocation = "gnuload" + loadCount++;
		}
		String str = "set output '../" + outputLocation + "'\n" +
		"set term png enhanced font '/usr/share/fonts/truetype/freefont/FreeSerif.ttf' 13\n" + 
		"set timestamp 0, -3.\n" +
		"set size 0.85, 0.85; set key left top\n" +
		"set title 'Sum of uniforms' 0, +.5\n" +
		"set xlabel 'x' 12, .6; set ylabel 'f(x)'\n" +
		"set yrange [0:*]\n" +
		"set y2label 'F(x)'; set ytics nomirror\n" +
		"set y2range [0:1]; set y2tics .2\n" +
		"plot '" + dataLocation + "' \\\n" +
		"     usi 1:2 axis x1y1 title 'f' with lines linetype 1 linewidth 2, \\\n" +
		" '' usi 1:3 axis x1y2 title 'F' with lines linetype 3 linewidth 3\n" +
		"#EOF 27-Jun-2009\n";
		FileUtils.generateTextFile(tempDir + configLocation, str);
		return configLocation;
	}

	private String makeGnuDataFile(int[] v, double ntrials, double xlowsum, double xuppsum) {
		try {
			String dataLocation;
			synchronized(dataCountLock) {
				dataLocation = "gnudata" + dataCount++;
			}
			
			FileWriter fstream = new FileWriter(tempDir + dataLocation);
			BufferedWriter out = new BufferedWriter(fstream);

			double klass = v.length -1;
			double a, b, c, sum = 0;
			double clwidth = (xuppsum - xlowsum) / klass;
			double b_mult = klass / (ntrials * (xuppsum - xlowsum));						
			for(int k = 0; k < v.length; k++) {
				sum += v[k];
				a = xlowsum + k*clwidth;
				b = v[k] * b_mult;
				c = sum/ntrials;
				out.write(a + " " + b + " " + c);
				out.newLine();
			}
			out.close();
			return dataLocation;
		} catch (FileNotFoundException e){
			System.err.println("FileNotFoundException occurred: " + e.getMessage());
		} catch (NumberFormatException e) {	
			System.err.println("NumberFormatException occurred: " + e.getMessage());
		} catch (IOException e) {
			System.err.println("IOException occurred: " + e.getMessage());
		}
		return null;
	}

	public void makeGraph(int[] dataAuxLocation, double ntrials, double xlowsum, double xuppsum,
			String outputLocation) {
		String dataLocation = makeGnuDataFile(dataAuxLocation, ntrials, xlowsum, xuppsum);
		String configLocation = makeGnuLoadFile(outputLocation, dataLocation);
		String cmd = gnuplotExe + " " + configLocation;
		try {
			Process app = Runtime.getRuntime().exec(cmd, null, new File(tempDir));
			app.waitFor();
		} catch (IOException e) {
			System.err.println("IOException occurred: " + e.getMessage());
		} catch (InterruptedException e) {
			System.err.println("InterruptedException occurred: " + e.getMessage());
		}
	}
	
}



